package cn.oms.oms.service.impl;

import cn.oms.oms.entity.*;
import cn.oms.oms.exception.ServiceException;
import cn.oms.oms.mapper.*;
import cn.oms.oms.service.IAdmissionService;
import cn.oms.oms.utils.TimeTool;
import cn.oms.oms.vo.AdmissionVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author AllenChen曾晨
 * @since 2022-04-29
 */
@Service
@Slf4j
public class AdmissionServiceImpl extends ServiceImpl<AdmissionMapper, Admission> implements IAdmissionService {

    @Autowired
    private AdmissionMapper admissionMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AppointmentMapper appointmentMapper;

    @Autowired
    private PatientMapper patientMapper;

    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private StaffMapper staffMapper;

    /**
     * 查询入院登记列表
     * @param admissionVo
     * @return
     */
    @Override
    public PageInfo<Admission> selectAdmissionList(AdmissionVo admissionVo) {

        QueryWrapper<Admission> query = new QueryWrapper<>();

        if (StringUtil.isNotEmpty(admissionVo.getPatientName())) {
            query.like("patientName",admissionVo.getPatientName());
        }

        if (StringUtil.isNotEmpty(admissionVo.getSelectAdmissionTime())){
            // 获取前端日期
            String date = admissionVo.getSelectAdmissionTime();
            // 05-04-2022
            date = TimeTool.formattingTime(date);

            System.out.println("date = " + date);

            Date simpleDate = new Date();
            try {
                simpleDate = new SimpleDateFormat("yyyy-MM-dd").parse(date);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            System.out.println("simpleDate = " + simpleDate);

            //日期格式转换
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(simpleDate);

            // 获取当天开始时间
            calendar.set(Calendar.HOUR_OF_DAY,0);
            calendar.set(Calendar.MINUTE,0);
            calendar.set(Calendar.SECOND,0);
            Date startTime = calendar.getTime();
            System.out.println("startTime = " + startTime);

            String startTimeStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(startTime);
            System.out.println("startTimeStr = " + startTimeStr);

            // 获取当天结束时间
            calendar.set(Calendar.HOUR_OF_DAY,23);
            calendar.set(Calendar.MINUTE,59);
            calendar.set(Calendar.SECOND,59);
            Date endTime = calendar.getTime();
            System.out.println("endTime = " + endTime);

            String endTimeStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(endTime);
            System.out.println("endTimeStr = " + endTimeStr);

            // 加入条件判断查询语句
            query.ge("createTime",startTimeStr);
            query.le("createTime",endTimeStr);
        }

        query.eq("deleteFlag",0);
        PageHelper.startPage(admissionVo.getPageNum(),admissionVo.getPageSize());

        List<Admission> admissionList = admissionMapper.selectList(query);
        for (Admission admission: admissionList){
            Admission admission1 = admissionParamFormat(admission);
            BeanUtils.copyProperties(admission1,admission);
        }

        return new PageInfo<>(admissionList);
    }

    /**
     * 根据入院号查详情
     * @param admissionVo
     * @return
     */
    @Override
    public Admission selectAdmissionDetail(AdmissionVo admissionVo) {
        if (admissionVo.getAdmissionId()==null||"".equals(admissionVo.getAdmissionId())){
            throw new ServiceException("查询参数异常，入院号不能为空");
        }
        QueryWrapper<Admission> query = new QueryWrapper<>();
        query.eq("admissionId",admissionVo.getAdmissionId());
        query.eq("deleteFlag",0);
        Admission admission = admissionMapper.selectOne(query);
        if (admission==null){
            throw new ServiceException("查询参数异常，无法找到入院信息");
        }

        Admission admission1 = admissionParamFormat(admission);

        return admission1;
    }


    /**
     * 新增入院登记
     * @param admissionVo
     * @return
     */
    @Override
    public String addAdmission(AdmissionVo admissionVo) {

        Admission admission = new Admission();
        if (admissionVo.getAppointmentId()!=null&&!"".equals(admissionVo.getAppointmentId())){
            admission.setAppointmentId(admissionVo.getAppointmentId());
        }
        // 根据预约号找患者
        QueryWrapper<Appointment> query = new QueryWrapper<>();
        query.eq("appointmentId",admissionVo.getAppointmentId());
        query.eq("deleteFlag",0);
        Appointment appointment = appointmentMapper.selectOne(query);
        if (appointment==null){
            throw new ServiceException("预约不存在");
        }
        Integer patientId = appointment.getPatientId();
        if (patientId==null||"".equals(patientId)){
           throw new ServiceException("参数异常，预约不存在");
        }
        admission.setPatientId(patientId);

        // 根据患者ID找患者名称
        QueryWrapper<Patient> query1 = new QueryWrapper<>();
        query1.eq("patientId",patientId);
        query1.eq("deleteFlag",0);
        Patient patient = patientMapper.selectOne(query1);
        String patientName = patient.getPatientName();
        if (StringUtil.isEmpty(patientName)){
            throw new ServiceException("参数异常，患者不存在");
        }
        admission.setPatientName(patientName);

        if (admissionVo.getAppointmentType()!=null&&!"".equals(admissionVo.getAppointmentType())){
            admission.setAppointmentType(admissionVo.getAppointmentType());
        }
        if (admissionVo.getDepartmentId()!=null&&!"".equals(admissionVo.getDepartmentId())){
            admission.setDepartmentId(admissionVo.getDepartmentId());
        }
        if (admissionVo.getStaffId()!=null&&!"".equals(admissionVo.getStaffId())){
            admission.setStaffId(admissionVo.getStaffId());
        }
        if (admissionVo.getFeeType()!=null&&!"".equals(admissionVo.getFeeType())){
            admission.setFeeType(admissionVo.getFeeType());
        }
        if (StringUtil.isNotEmpty(admissionVo.getAdmissionSymptoms())){
            admission.setAdmissionSymptoms(admissionVo.getAdmissionSymptoms());
        }

        admission.setCreateTime(new Date());
        admission.setDeleteFlag(0);

        int num = admissionMapper.insert(admission);
        if (num!=1){
            throw new ServiceException("数据库新增异常！！！");
        }

        // 新增完成 修改绑定的预约
        appointment.setAppointmentFlag(1);
        num = appointmentMapper.updateById(appointment);
        if (num!=1){
            throw new ServiceException("数据库修改异常！！！");
        }

        return "ok";
    }

    /**
     * 修改入院登记
     * @param admissionVo
     * @return
     */
    @Override
    public String updateAdmission(AdmissionVo admissionVo) {
        Admission admission = new Admission();

        BeanUtils.copyProperties(admissionVo,admission);

        int num = admissionMapper.updateById(admission);

        if (num!=1){
            throw new ServiceException("数据库修改异常！！！");
        }

        return "ok";
    }

    /**
     * 删除入院登记
     * @param id
     * @return
     */
    @Override
    public String deleteAdmission(Integer id) {
        if (id==null||"".equals(id)){
            throw new ServiceException("参数异常，入院号不能为空");
        }
        QueryWrapper<Admission> query = new QueryWrapper<>();
        query.eq("admissionId",id);
        query.eq("deleteFlag",id);
        Admission admission = admissionMapper.selectOne(query);
        if (admission==null){
            throw  new ServiceException("参数异常，未查询到入院登记信息");
        }
        admission.setDeleteFlag(1);
        int num = admissionMapper.updateById(admission);

        if (num!=1){
            throw new ServiceException("数据库修改异常！！！");
        }

        return "ok";
    }

    /**
     * 参数格式化返回
     */
    public Admission admissionParamFormat(Admission admission){
        // 加科室名称
        Integer departmentId = admission.getDepartmentId();
        QueryWrapper<Department> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",departmentId);
        queryWrapper.eq("deleteFlag",0);
        Department department = departmentMapper.selectOne(queryWrapper);
        if (department!=null){
            admission.setDepartmentName(department.getDepartmentName());
        }

        // 加医生名称
        Integer staffId = admission.getStaffId();
        QueryWrapper<Staff> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("staffId",staffId);
        queryWrapper1.eq("deleteFlag",0);
        Staff staff = staffMapper.selectOne(queryWrapper1);
        if (staff!=null){
            admission.setStaffName(staff.getStaffName());
        }

        // 加门诊类型名称
        if (admission.getAppointmentType()==0){
            admission.setAppointmentTypeName("门诊");
        }
        if (admission.getAppointmentType()==1){
            admission.setAppointmentTypeName("住院");
        }

        // 加费用类型名称
        if (admission.getFeeType()==0){
            admission.setFeeTypeName("自费");
        }

        // 日期格式化
        Date createTime = admission.getCreateTime();
        String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(createTime);
        admission.setReturnCreateTime(date);
        return admission;
    }


}
